import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import BottomNav from '../components/BottomNav';
import { LockClosedIcon, PlusIcon, CheckIcon, EyeIcon, EyeSlashIcon, XMarkIcon as XIcon } from '@heroicons/react/24/outline';
import { CredentialService } from '../api/credentials';
import type { AddUserCredentialParams, UserCredential } from '../api/credentials';


// 模拟加密函数（实际应用中应使用真实的加密算法）
const encryptPassword = (password: string): string => {
  // 注意：这只是一个示例，实际应用中应使用安全的加密算法
  // 这里返回原始字符串，由后端进行实际加密
  return password;
};

export default function PasswordManagerPage() {
  // 状态管理
  const [showModal, setShowModal] = useState(false);
  const [platformName, setPlatformName] = useState('');
  const [platformUrl, setPlatformUrl] = useState('');
  const [accountUsername, setAccountUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [credentials, setCredentials] = useState<UserCredential[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // 获取用户凭证信息
  useEffect(() => {
    const fetchCredentials = async () => {
      try {
        setIsLoading(true);
        // 获取当前用户ID（实际应用中应从认证信息中获取）
        const currentUserId = 1; // 这里使用硬编码的用户ID，实际应从登录信息中获取
        
        console.log('[PasswordManagerPage] 开始获取用户凭证，用户ID:', currentUserId);
        // 调用API获取凭证
        const response = await CredentialService.getUserCredentialsByUserId(currentUserId);
        
        // 检查响应是否成功
        if (response.code === '200' && Array.isArray(response.data)) {
          // 处理平台URL中的空格问题
          const processedCredentials = response.data.map(cred => ({
            ...cred,
            platformUrl: cred.platformUrl ? cred.platformUrl.trim() : null,
            encryptedPassword: '••••••••' // 显示为星号
          }));
          setCredentials(processedCredentials);
        } else {
          console.error('获取凭证失败:', response.msg);
          setError(response.msg || '获取凭证信息失败');
          // 如果没有数据，设置空数组
          setCredentials([]);
        }
      } catch (err) {
        console.error('获取凭证时发生错误:', err);
        // 提供更友好的错误信息
        const errorMessage = err instanceof Error ? err.message : '网络请求失败，请稍后重试';
        setError(errorMessage);
        // 错误情况下也设置空数组，避免页面白屏
        setCredentials([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchCredentials();
  }, []);

  // 处理添加凭证
  const handleAddCredential = async () => {
    // 重置错误状态
    setError('');
    
    // 表单验证
    if (!platformName.trim()) {
      setError('请输入平台名称');
      return;
    }
    if (!accountUsername.trim()) {
      setError('请输入账号用户名');
      return;
    }
    if (!password.trim()) {
      setError('请输入密码');
      return;
    }
    
    try {
      setIsSubmitting(true);
      
      // 获取当前用户ID（实际应用中应从认证信息中获取）
      const currentUserId = 1; // 这里使用硬编码的用户ID，实际应从登录信息中获取
      
      // 构建请求参数
      const params: AddUserCredentialParams = {
        userId: currentUserId,
        platformName: platformName.trim(),
        platformUrl: platformUrl.trim() || undefined,
        accountUsername: accountUsername.trim(),
        encryptedPassword: encryptPassword(password)
      };
      
      // 调用API添加凭证
      const response = await CredentialService.addUserCredential(params);
      
      // 检查响应是否成功
      if (response.code === '200' && response.data) {
        // 添加到本地列表
        setCredentials([...credentials, {
          ...response.data,
          encryptedPassword: '••••••••' // 显示为星号
        }]);
        
        // 重置表单
        resetForm();
        
        // 关闭模态框
        setShowModal(false);
      } else {
        setError(response.msg || '添加失败');
      }
    } catch (err) {
      console.error('添加凭证时发生错误:', err);
      setError(err instanceof Error ? err.message : '添加失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };
  
  // 重置表单
  const resetForm = () => {
    setPlatformName('');
    setPlatformUrl('');
    setAccountUsername('');
    setPassword('');
    setError('');
  };
  
  // 处理模态框关闭
  const handleCloseModal = () => {
    resetForm();
    setShowModal(false);
  };

  return (
    <div className="pb-16">
      <motion.div 
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        className="p-4 max-w-md mx-auto"
      >
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold dark:text-white">密码管理</h1>
          <button 
            className="p-2 rounded-full bg-primary text-white hover:bg-primary/90 transition-colors"
            onClick={() => setShowModal(true)}
          >
            <PlusIcon className="w-5 h-5" />
          </button>
        </div>
        
        {isLoading ? (
          <div className="text-center py-10 text-gray-500 dark:text-gray-400">
            加载中...
          </div>
        ) : credentials.length === 0 ? (
          <div className="text-center py-10 text-gray-500 dark:text-gray-400">
            暂无保存的账号密码
          </div>
        ) : (
          <div className="space-y-3">
            {credentials.map((credential) => (
              <motion.div 
                key={credential.id}
                whileHover={{ scale: 1.02 }}
                className="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-100 dark:border-gray-700"
              >
                <div className="flex items-center">
                  <div className="p-2 mr-3 rounded-lg bg-gray-100 dark:bg-gray-700">
                    <LockClosedIcon className="w-5 h-5 text-primary" />
                  </div>
                  <div className="flex-1">
                    <h3 className="font-medium dark:text-white">{credential.platformName}</h3>
                    <p className="text-sm text-gray-500 dark:text-gray-400">{credential.accountUsername}</p>
                  </div>
                  <span className="text-xs text-gray-400 cursor-pointer hover:text-primary transition-colors">查看</span>
                </div>
              </motion.div>
            ))}
          </div>
        )}
      </motion.div>
      
      {/* 添加凭证模态框 */}
      {showModal && (
        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50"
        >
          <motion.div 
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            className="bg-white dark:bg-gray-800 rounded-lg shadow-lg w-full max-w-md overflow-hidden"
          >
            <div className="flex justify-between items-center p-4 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold dark:text-white">添加账号密码</h2>
              <button 
                onClick={handleCloseModal}
                className="p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                <XIcon className="w-5 h-5 dark:text-gray-400" />
              </button>
            </div>
            
            <div className="p-4">
              {error && (
                <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-md text-sm">
                  {error}
                </div>
              )}
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">平台名称</label>
                  <input
                    type="text"
                    value={platformName}
                    onChange={(e) => setPlatformName(e.target.value)}
                    placeholder="如：微信、GitHub"
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">平台网址（可选）</label>
                  <input
                    type="text"
                    value={platformUrl}
                    onChange={(e) => setPlatformUrl(e.target.value)}
                    placeholder="如：https://github.com"
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">账号用户名</label>
                  <input
                    type="text"
                    value={accountUsername}
                    onChange={(e) => setAccountUsername(e.target.value)}
                    placeholder="如：username@example.com"
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">密码</label>
                  <div className="relative">
                    <input
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary pr-10"
                    />
                    <button 
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      {showPassword ? (
                        <EyeSlashIcon className="w-5 h-5" />
                      ) : (
                        <EyeIcon className="w-5 h-5" />
                      )}
                    </button>
                  </div>
                </div>
              </div>
            </div>
            
            <div className="p-4 border-t border-gray-200 dark:border-gray-700 flex justify-end space-x-3">
              <button 
                onClick={handleCloseModal}
                disabled={isSubmitting}
                className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
              >
                取消
              </button>
              <button 
                onClick={handleAddCredential}
                disabled={isSubmitting}
                className="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors flex items-center"
              >
                {isSubmitting ? (
                  <span className="animate-spin mr-2 h-4 w-4 border-2 border-white border-opacity-50 border-t-white rounded-full"></span>
                ) : (
                  <CheckIcon className="w-4 h-4 mr-2" />
                )}
                添加
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
      
      <BottomNav />
    </div>
  );
}